package com.atguigu.gulimall.order.web;

import com.atguigu.common.exception.NoStockException;
import com.atguigu.gulimall.order.service.OrderService;
import com.atguigu.gulimall.order.vo.OrderConfirmVo;
import com.atguigu.gulimall.order.vo.OrderSubmitVo;
import com.atguigu.gulimall.order.vo.SubmitOrderResponseVo;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import java.util.concurrent.ExecutionException;

/**
 * @create: 2024/9/11
 * @author: gyhe10
 * @description:
 **/

@Controller
public class OrderWebController {

    @Resource
    private OrderService orderService;

    /**
     * 展示订单确认页
     * @param model
     * @return
     */
    @GetMapping("/toTrade")
    public String toTrade(Model model) throws ExecutionException, InterruptedException {
        // 展示订单确认页所需要的数据
        OrderConfirmVo confirmVo = orderService.confirmOrder();
        model.addAttribute("orderConfirmData", confirmVo);
        return "confirm";
    }

    /**
     * 提交订单
     *   1. 创建订单，包括验证令牌、验价、锁定库存...
     *   2. 创建订单成功，重定向到支付页
     *   3. 创建订单失败，回到订单确认页，提醒用户重新确认订单信息
     * @param submitVo
     * @return
     */
    @PostMapping("/submitOrder")
    public String submitOrder(OrderSubmitVo submitVo, Model model, RedirectAttributes redirectAttributes) {
        try {
            SubmitOrderResponseVo responseVo = orderService.submitOrder(submitVo);
            if (responseVo.getCode() == 0) {
                // 创建订单成功，跳转到支付页
                model.addAttribute("submitOrderResp", responseVo.getOrder());
                return "pay";
            } else {
                String msg = "下单失败：";
                switch (responseVo.getCode()) {
                    case 1: msg += "订单信息超时，请刷新页面、重新提交"; break;
                    case 2: msg += "订单商品价格发生变化，请确认后再次提交"; break;
                    case 3: msg += "锁定库存失败，商品库存不足"; break;
                }
                redirectAttributes.addFlashAttribute("msg", msg);
                // 创建订单失败，重定向到订单确认页，重新确认订单信息
                return "redirect:http://order.gulimall.com/toTrade";
            }
        } catch (Exception e) {
            if (e instanceof NoStockException) {
                String message = e.getMessage();
                redirectAttributes.addFlashAttribute("msg", message);
            }
            return "redirect:http://order.gulimall.com/toTrade";
        }
    }
}
